package cn.wolfcode.service.impl;

import cn.wolfcode.domain.CustomerTransfer;
import cn.wolfcode.domain.Employee;
import cn.wolfcode.mapper.CustomerMapper;
import cn.wolfcode.mapper.CustomerTransferMapper;
import cn.wolfcode.qo.QueryObject;
import cn.wolfcode.service.CustomerTransferService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class CustomerTransferServiceImpl implements CustomerTransferService {

    @Autowired
    private CustomerTransferMapper customerTransferMapper;

    @Autowired
    private CustomerMapper customerMapper;

    @Override
    public void save(CustomerTransfer customerTransfer) {
        customerTransferMapper.insert(customerTransfer);
    }

    @Override
    public void delete(Long id) {
        customerTransferMapper.deleteByPrimaryKey(id);
    }

    @Override
    public void update(CustomerTransfer customerTransfer) {
        customerTransferMapper.updateByPrimaryKey(customerTransfer);
    }

    @Override
    public CustomerTransfer get(Long id) {
        return customerTransferMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<CustomerTransfer> listAll() {
        return customerTransferMapper.selectAll();
    }

    @Override
    public PageInfo<CustomerTransfer> query(QueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(), qo.getPageSize(), "operate_time desc"); //对下一句sql进行自动分页
        List<CustomerTransfer> customerTransfers = customerTransferMapper.selectForList(qo); //里面不需要自己写limit
        return new PageInfo<CustomerTransfer>(customerTransfers);
    }

    @Override
    public void saveOrUpdate(CustomerTransfer customerTransfer) {
        Employee employee = (Employee) SecurityUtils.getSubject().getPrincipal();
        //设置操作者
        customerTransfer.setOperator(employee);
        //设置操作时间
        customerTransfer.setOperateTime(new Date());
        //移交的操作
        customerMapper.updateBySellerId(customerTransfer.getCustomer().getId(), customerTransfer.getNewSeller().getId());
        if (customerTransfer.getId() != null) {
            customerTransferMapper.updateByPrimaryKey(customerTransfer);
        } else {
            customerTransferMapper.insert(customerTransfer);
        }
    }
}
